package com.ch.clinking.adapter.Order;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ch.clinking.ClinkingApplication;
import com.ch.clinking.R;
import com.ch.clinking.Utils.NetUtils.OkHttpUtil;
import com.ch.clinking.ViewHolder.OrderAutoListViewHolder;
import com.ch.clinking.bean.MerSaleDTO;
import com.ch.clinking.bean.OrderDto;
import com.ch.clinking.bean.OrderInfo;
import com.ch.clinking.bean.SaleInfo;

import java.lang.reflect.Method;
import java.util.List;

public class AddOrderAutoAdapter extends RecyclerView.Adapter<OrderAutoListViewHolder> {

    public List<OrderInfo> orderInfoList;
    private LayoutInflater layoutInflater;
    private Activity context;
    private Integer operation = 0;
    public Integer batch = 0;
    public Integer changeOperateNum = 1;
    public MerSaleDTO merSaleDTO;

    private ClinkingApplication app;

    public AddOrderAutoAdapter(Activity context, List<OrderInfo> orderInfoList, MerSaleDTO merSaleDTO) {
        this.orderInfoList = orderInfoList;
        this.context = context;
        this.merSaleDTO = merSaleDTO;
        this.app = ClinkingApplication.getInstance();
        layoutInflater = LayoutInflater.from(context);
    }


    @NonNull
    @Override
    public OrderAutoListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.list_add_order_auto_sku_layout, parent, false);
        return new OrderAutoListViewHolder(view);
    }

    @Override
    public int getItemCount() {
        return orderInfoList.size();
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull OrderAutoListViewHolder holder, @SuppressLint("RecyclerView") int position) {

        OrderInfo orderInfo = orderInfoList.get(position);
//        Glide.with(context).load(OkHttpUtil.getInstance().getIMG_URL() + orderInfo.getImage()).into(holder.image);
        holder.title.setText(orderInfo.getTitle());

        // 计算各尺码下单数
        setAutoNum(orderInfo, holder.auto1Day, holder.auto2Day, holder.auto3Day);


        holder.addNum.setText(Integer.toString(orderInfo.getFinalNum()));

//        // 设置默认占位图片
//        Glide.with(context)
//                .load(R.drawable.appicon)
//                .into(holder.image);
//
//        // 加载图片
//        Glide.with(context)
//                .load(OkHttpUtil.getInstance().getIMG_URL() + orderInfo.getImage())
//                .placeholder(R.drawable.appicon)
//                .diskCacheStrategy(DiskCacheStrategy.ALL)  // 缓存策略：缓存原始图片和转换后的图片
//                .thumbnail(0.5f)  // 缩略图大小
//                .error(R.drawable.appicon)
//                .into(holder.image);

        // 清除旧的TextWatcher
        if (holder.addNum.getTag() instanceof TextWatcher) {
            holder.addNum.removeTextChangedListener((TextWatcher) holder.addNum.getTag());
        }

        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String c = editable.toString();
                if (c.equals("")) {
                    c = "0";
                }
                int change = Integer.parseInt(c);
                orderInfo.setFinalNum(change);
            }
        };

        holder.addNum.addTextChangedListener(watcher);
        holder.addNum.setTag(watcher);

        holder.toZero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                holder.addNum.setText("0");
            }
        });

    }

    private void setAutoNum(OrderInfo orderInfo, TextView auto1Day, TextView auto2Day, TextView auto3Day) {
        try {

            // 需要处理的尺码列表
            String[] sizes = {"XXS", "XS", "S", "M", "L", "XL", "XXL", "Plus_0XL", "Plus_1XL", "Plus_2XL", "Plus_3XL", "Plus_4XL", "Plus_5XL", "Plus_6XL"};

//            for (String size : sizes) {

            // 使用反射调用 isActivate_XXS、getInHouseStock_XXS 等方法
            Method isActivateMethod = merSaleDTO.getClass().getMethod("isActivate_" + orderInfo.getTitle());
            boolean isActivated = (boolean) isActivateMethod.invoke(merSaleDTO);

            if (isActivated) {

                boolean saleFlag = false;
                // 处理销售信息
                for (SaleInfo info : merSaleDTO.getSaleInfoList()) {
                    if (info.getClassName().contains("-" + orderInfo.getTitle())) {

                        saleFlag = true;

                        Method getStockMethod = merSaleDTO.getClass().getMethod("getInHouseStock_" + orderInfo.getTitle());
                        int self_stock = (int) getStockMethod.invoke(merSaleDTO);

                        // 处理订单信息
                        int finalOrderSizeNum = 0;
                        for (OrderDto orderDto : merSaleDTO.getOrderList()) {
                            Method getOrderMethod = orderDto.getClass().getMethod("get" + orderInfo.getTitle());
                            Method getMakeMethod = orderDto.getClass().getMethod("getMake_" + orderInfo.getTitle());

                            if ((int) getMakeMethod.invoke(orderDto) != 0) {
                                finalOrderSizeNum += (int) getMakeMethod.invoke(orderDto);
                            } else {
                                finalOrderSizeNum += (int) getOrderMethod.invoke(orderDto);
                            }
                        }

                        String today = CalculateMakeOrder(info.getWarehouseInventoryNum(), info.getWaitReceiveNum(), self_stock, info.getLastSevenDaysSaleVolume(), app.productionCycle, app.replenishDay, finalOrderSizeNum);
                        String _1day = CalculateMakeOrder(info.getWarehouseInventoryNum(), info.getWaitReceiveNum(), self_stock, info.getLastSevenDaysSaleVolume(), app.productionCycle + 1, app.replenishDay, finalOrderSizeNum);
                        String _2day = CalculateMakeOrder(info.getWarehouseInventoryNum(), info.getWaitReceiveNum(), self_stock, info.getLastSevenDaysSaleVolume(), app.productionCycle + 2, app.replenishDay, finalOrderSizeNum);
                        String _3day = CalculateMakeOrder(info.getWarehouseInventoryNum(), info.getWaitReceiveNum(), self_stock, info.getLastSevenDaysSaleVolume(), app.productionCycle + 3, app.replenishDay, finalOrderSizeNum);

                        auto1Day.setText(_1day);
                        auto2Day.setText(_2day);
                        auto3Day.setText(_3day);

                        orderInfo.setFinalNum(Integer.parseInt(today));
                    }
                }
                if (!saleFlag) {
                    auto1Day.setText("0");
                    auto2Day.setText("0");
                    auto3Day.setText("0");

                    orderInfo.setFinalNum(Integer.parseInt("0"));
                }

            }

//            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private String CalculateMakeOrder(int temu_stock, int on_way, int self_stock, int S_i, int W, int D, int ZZ) {

        double S = 0;
        if (S_i != 0) {
            S = Double.parseDouble(String.valueOf(S_i)) / 7.0;
        }

        System.out.println("temu_stock:"+String.valueOf(temu_stock)+" on_way:"+String.valueOf(on_way)+" self_stock:"+String.valueOf(self_stock)+" S:"+String.valueOf(S)+" S_i:"+String.valueOf(S_i)+" W:"+String.valueOf(W)+" D:"+String.valueOf(D)+" ZZ:"+String.valueOf(ZZ));


        // S 平均销售数量
        // W = 7 生产周期
        // D = 5 每单补货量的天数
        // ZZ 真正做的数量
        double Num = 0; // 需要下单的数量

        while ((temu_stock + on_way + self_stock + ZZ + Num - S * W) < 0) {
            Num += D * S;
            System.out.println((temu_stock + on_way + self_stock + ZZ + Num - S * W));
            System.out.println(Num);
        }

//        if ((temu_stock + on_way + self_stock - S * W) <= 0) {
//            binding.calculateMakeOrderUrgent.setText("是");
//        } else {
//            binding.calculateMakeOrderUrgent.setText("否");
//        }


        @SuppressLint("DefaultLocale") String formattedValue = String.format("%.0f", Num);

        System.out.println(formattedValue);

        return formattedValue;

    }

    @SuppressLint("NotifyDataSetChanged")
    public void flash() {
        notifyDataSetChanged();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        ImageView image;
        TextView title, auto1Day, auto2Day, auto3Day;
        EditText addNum;
        Button toZero;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

//            this.image = itemView.findViewById(R.id.add_order_auto_sku_img);
            this.title = itemView.findViewById(R.id.add_order_auto_sku_title);
            this.auto1Day = itemView.findViewById(R.id.add_order_auto_sku_1_day_num);
            this.auto2Day = itemView.findViewById(R.id.add_order_auto_sku_2_day_num);
            this.auto3Day = itemView.findViewById(R.id.add_order_auto_sku_3_day_num);
            this.addNum = itemView.findViewById(R.id.add_order_auto_sku_final_num);
            this.toZero = itemView.findViewById(R.id.add_order_auto_to_zero);


        }
    }

}
